package pojo;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestUser {
	private static EntityManagerFactory factory;
	private EntityManager manager;
	@BeforeClass
	public static void init(){
		factory=Persistence.createEntityManagerFactory("john");
	}
	@AfterClass
	public static void destroy(){
		factory.close();
	}
	@Before
	public void start(){
		manager=factory.createEntityManager();
	}
	@After
	public void end(){
		manager.close();
	}
	
	@Test
	public void testAdd(){
		User u = new User();
		u.setId(2);
		u.setCname("tom");
		u.setAge(1);
		Address add1 = new Address();
		add1.setCity("zhuh1");add1.setZipcode("1000");
		Address add2 = new Address();
		add2.setCity("zhuh2");add2.setZipcode("1000");
		u.getAddrs().add(add1);u.getAddrs().add(add2);
		
		u.getTels().add("13267666");
		u.getTels().add("13267777");
		EntityTransaction tx = manager.getTransaction();
		tx.begin();
		manager.persist(u);
		tx.commit();
	}
	
	@Test
	public void testQuery(){
		User u = manager.find(User.class, 1);
		System.out.println(u);
//		for(String s : u.getTels()){
//			System.out.println(s);
//		}
	}
	
	@Test
	public void testUpdate(){
		User u = manager.find(User.class, 1);
		EntityTransaction tx = manager.getTransaction();
		tx.begin();
		u.getTels().clear();
		tx.commit();
	}
	
	@Test
	public void testDelete(){
		User u = manager.find(User.class, 2);
		Set<Address> s =u.getAddrs();
		
		EntityTransaction tx = manager.getTransaction();
		tx.begin();
		manager.remove(u);
//		manager.remove(s);
		tx.commit();
	}
}
